// pages/user/order-list-spell/order-list-spell.js
import Toast from '../../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
import Dialog from '../../../miniprogram/miniprogram_npm/vant-weapp/dialog/dialog'
let app = getApp();
const moment = require('../../../utils/moment.min.js');
const STATUS_TEXT = {
  '-1': "已取消",
  0: "待付款",
  1: "待发货",
  2: "已发货",
  25: "部分发货",
  3: "已收货",
  4: "待退款",
  5: "售后中",
  6: "已完成",
}
const SPELLGROUPSTU_TEXT = {
  1: '待分享',
  2: '拼团成功',
  3: '拼团失败',
  4: '已取消',
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    globalConfig:  app.getGlobalConfig(),
    STATUS_TEXT,
    SPELLGROUPSTU_TEXT,
    tabActive: 0,
    tabsItem: [{
      name: '全部',
      status: '',
    },
      {
        name: '待付款',
        status: 0,
      },
      {
        name: '待分享',
        status: 1,
      },
      {
        name: '已成团',
        status: 2,
      },
    ],
    itemList: [],
    currPage: 1,
    perPage: 5,
    noMore: false,//false 还有更多数据，true 到底了
    isEmpty: false,//true  无数据
    timeData: {},//倒计时对象
    serverTime: null,//当前时间戳
  },

  //取消订单
  cancelOrder(event){
    let _this = this;
    let order = event.currentTarget.dataset.order;
    let index = event.currentTarget.dataset.index;

    if (order.status === 1) { //订单已支付
      let cancelAble = true;
      for (let goodsIndex = 0; goodsIndex < order.orderProducts.length; ++goodsIndex) {
        if (order.orderProducts[goodsIndex].uncancelable === 1) {//订单里存在不支持无理由退单
          cancelAble = false;
          break;
        }
      };
      if (!cancelAble) {
        Dialog.alert({
          message: '有不支持无理由退单商品，无法取消订单'
        });
        return;
      }
    }

    Dialog.confirm({
      message: '确定要取消该订单吗？',
    }).then(() => {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/order/cancel',
        data: {
          orderId: order.id,
        }
      }).then((res)=>{
        order.status = -1;
        order.orderProducts.forEach(goods => {
          goods.status = -1;
          goods.spellgroupStu = 4;
        });
        let orderProducts = 'itemList[' + index +'].orderProducts';
        let status = 'itemList[' + index +'].status';
        _this.setData({
          [orderProducts]:  order.orderProducts,
          [status]:  order.status,
        })
        Toast.success('已取消该订单');
      })
    }).catch(()=>{})

  },

  getGet(isPage){//isPage=true下一页，isPage=false第一页
    if (!isPage) this.setData({currPage: 1})
    let _this = this;
    let status = _this.data.tabsItem[_this.data.tabActive].status;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/order/list',
      data: {
        mid: _this.data.user.id,
        status: status,
        dispatchid: 2,//拼团订单
        offset: (_this.data.currPage - 1) * _this.data.perPage,
        limit: _this.data.perPage,
        orderType:3,
      },
      load: 1
    }).then(res =>{
      let tempList = res.data.data.rows;
      //处理时间
      tempList.filter((item,index)=>{
        tempList[index].orderProducts[0].upEndTime = (moment(item.orderProducts[0].upEndTime).valueOf() - _this.data.serverTime) > 0 ? moment(item.orderProducts[0].upEndTime).valueOf() - _this.data.serverTime : 0;
      })
      //下一页的数据拼接在原有数据后面
      if (isPage) {
        _this.setData({
          itemList: _this.data.itemList.concat(tempList)
        })
      }
      //第一页数据直接赋值
      else {
        _this.setData({
          itemList: tempList,
          isEmpty: !tempList.length > 0,
          noMore: false,
        })
      }
      //如果返回的数据为空，那么就没有下一页了
      if (tempList.length == 0) {
        _this.setData({
          noMore: true,
        })
      }
    })
  },

  //单品取消
  singleCancel(event){
    let _this = this;
    let order = event.currentTarget.dataset.order;
    let goods = event.currentTarget.dataset.goods;
    let index = event.currentTarget.dataset.index;
    let itemIndex = event.currentTarget.dataset.itemindex;

    Dialog.confirm({
      message: '确定要取消商品吗？',
    }).then(() => {
      app.requestUrl({
        method: 'POST',
        url: '/wxapi/order/goods/cancel',
        data: {
          goodsId: goods.id,
        }
      }).then((res)=>{
        let goodsStatus = 'itemList[' + index +'].orderProducts['+ itemIndex +'].status';
        let spellgroupStu = 'itemList[' + index +'].orderProducts['+ itemIndex +'].spellgroupStu';
        _this.setData({
          [goodsStatus]: -1,
          [spellgroupStu]: 4
        })
        Toast.success('已取消该商品');
      })
    }).catch(()=>{})

  },

  tabChange(event){
    this.setData({
      tabActive: event.detail.index,
      serverTime: Date.parse(new Date()),
    })
    this.getGet(false)
  },

  //查看详情
  toOrderInfo(event){
    let status = event.currentTarget.dataset.status;
//    if(status == -1)
//      wx.navigateTo({
//        url: '/pages/user/order-info/order-info?payId=' + event.currentTarget.dataset.id
//      })
//     else
      wx.navigateTo({
        url: '/subIndex/index/good-spell/good-spell?orderId=' + event.currentTarget.dataset.sgorderid + '&promoter=' + event.currentTarget.dataset.promoter + '&productId=' + event.currentTarget.dataset.productid + '&orderStatus=' + status
      })
  },
  //去支付
  toPay(event){
    wx.navigateTo({
      url: '/pages/user/order-info/order-info?payId=' + event.currentTarget.dataset.id
    })
  },

  //监听倒计时
  timeChange(e) {
    this.setData({
      timeData: e.detail
    });
  },
  //倒计时结束
  timeFinish(){
    this.setData({
      serverTime: Date.parse(new Date()),
    })
    this.getGet(false);
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    this.setData({
      user: app.getUser(),
      tabActive: event.active || 0,
      serverTime: Date.parse(new Date()),
    })
    this.getGet(false);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.noMore) {
      this.setData({
        currPage: this.data.currPage + 1
      })
      this.getGet(true)//传true代表进行下一页
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})